import 'dart:async';
import 'dart:io';

import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:image_picker/image_picker.dart';
import 'package:wu_you/data/cache/id_cache.dart';
import 'package:wu_you/data/repository/trad_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/model/user/trad_model.dart';
import 'package:wu_you/page/trad/page_order_appeal.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/state/bloc/http_bloc.dart';
import 'package:wu_you/state/bloc/trad_bloc.dart';
import 'package:wu_you/utils/navigator_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/utils/utils_image.dart';
import 'package:wu_you/widgets/http_status_widget.dart';
import 'package:wu_you/utils/extension_utils.dart';
import 'package:wu_you/widgets/list_time_widget.dart';
import 'package:wu_you/widgets/page_image_net.dart';
import 'package:wu_you/widgets/pay_dialog.dart';
import 'package:wu_you/widgets/text_form_field_widget.dart';

///订单详情
class OrderDetailPage extends StatefulWidget{
  final String id;
  OrderDetailPage({Key key,this.id}):super(key: key);
  @override
  OrderDetailPageState createState() => OrderDetailPageState();
}
class OrderDetailPageState extends State<OrderDetailPage>{

  final _picker = ImagePicker();
  String userId;
  @override
  void initState() {
    super.initState();
    _getUserId();
  }
  _getUserId(){
    UserIdCache().get().then((value){
      setState(() {
        userId = value;
      });
    });
  }

  String _select = "0";

  // String alipayUploadUrl;
  // String wxUploadUrl;

  BuildContext ctx;
  int current = 0;

  var message;

  String uploadBuyImage;



  String remainTimeStr = '';
  Timer _timer;

  //倒计时
  void startCountDown(int time) {
    // 重新计时的时候要把之前的清除掉
    if (_timer != null) {
      if (_timer.isActive) {
        _timer.cancel();
        _timer = null;
      }
    }

    if (time <= 0) {
      return;
    }

    var countTime = time;
    const repeatPeriod = const Duration(seconds: 1);
    _timer = Timer.periodic(repeatPeriod, (timer) {
      if (countTime <= 0) {
        timer.cancel();
        timer = null;
        //待付款倒计时结束，可以在这里做相应的操作

        return;
      }
      countTime--;

      //外面传进来的单位是秒，所以需要根据总秒数，计算小时，分钟，秒
      int hour = (countTime ~/ 3600) % 24;
      int minute = countTime % 3600 ~/60;
      int second = countTime % 60;

      var str = '';
      if (hour > 0) {
        str = str + hour.toString()+':';
      }

      if (minute / 10 < 1) {//当只有个位数时，给前面加“0”，实现效果：“:01”,":02"
        str = str + '0' + minute.toString() + ":";
      } else {
        str = str + minute.toString() + ":";
      }

      if (second / 10 < 1) {
        str = str + '0' + second.toString();
      } else {
        str = str + second.toString();
      }

      setState(() {
        remainTimeStr = str;
      });

    });
  }
  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      if (_timer.isActive) {
        _timer.cancel();
        _timer = null;
      }
    }
  }
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    double width = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        title: Text("${message['trad71']}"),
      ),
      backgroundColor: Colors.white,
      body: RefreshIndicator(
        onRefresh: (){
          BlocProvider.of<OrderItemInfoBloc>(ctx).add(IdHttpEvent(int.parse(widget.id)));
          return Future.value(true);
        },
        child: SingleChildScrollView(
            physics: AlwaysScrollableScrollPhysics(),
            child: HttpWidget<TradOrderDetail, OrderItemInfoBloc>(
                create: (context) => OrderItemInfoBloc()..add(IdHttpEvent(int.parse(widget.id))),
                child: (context, data) {
                  ctx = context;
                  String skName;
                  String skBank;
                  String skCard;
                  String usdtUrl;
                  String alipayUrl;
                  String wxUrl;
                  String tngUrl;
                  // Widget alipayImage;
                  // Widget wxImage;

                  Widget uploadByImage;
                  if (userId == data.uid) { //判断是卖家买家
                    current = 2; //买家
                  } else {
                    current = 1;//卖家
                  }

                  if(data.payment != null){
                    data.payment.forEach((element) {
                      if(element.payment == "1"){
                        List<String> cl = element.content.split("|");
                        skBank = cl[0];
                        skName = cl[1];
                        skCard = cl[2];
                      }else if(element.payment == "2"){
                        alipayUrl = element.content;
                      }else if(element.payment == "3"){
                        wxUrl = element.content;
                      }else if(element.payment == "4"){
                        usdtUrl = element.content;
                      }else if(element.payment == "5"){
                        tngUrl = element.content;
                      }
                    });
                  }

                  if(uploadBuyImage == null){
                    uploadByImage = Image.asset(Utils.getImgPath("ic_complaints_add"),width: 100,height: 100,);
                  }else{
                    uploadByImage = Image.network(uploadBuyImage,width: 100,height: 100,fit: BoxFit.fill,);
                  }
                  // if(wxUploadUrl == null){
                  //   wxImage = Image.asset(Utils.getImgPath("ic_complaints_add"),width: 100,height: 100,);
                  // }else{
                  //   wxImage = Image.network(wxUploadUrl,width: 100,height: 100,fit: BoxFit.fill,);
                  // }



                  bool paySelectView = true;
                  bool payImageView = true;
                  if((data.pay_status == "0" || data.pay_status == "2") && current != 1 && data.status != "30"){
                    paySelectView = false;
                  }else{
                    paySelectView = true;
                    if(data.certificate != null && data.certificate.length > 0){
                      payImageView = false;
                    }else{
                      payImageView = true;
                    }
                  }

                  int createTime = int.parse(data.create_time) * 1000;
                  var startDate = new DateTime.fromMillisecondsSinceEpoch(createTime);
                  var endDate = new DateTime.now();
                  var timeOut = (20 * 60) - endDate.difference(startDate).inSeconds;


                  startCountDown(timeOut);


                  Widget selectView;
                  if(paySelectView == false){
                    selectView = Container(
                      alignment: Alignment.centerRight,
                      child: Wrap(
                        spacing: 2,
                        children: data.payment.map((e){
                          return Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              SizedBox(
                                child: Radio(
                                    value: e.payment,
                                    groupValue: _select,
                                    onChanged: (value){
                                      setState(() {
                                        _select = value;
                                      });
                                    }
                                ),
                                width: 30,
                                height: 30,
                              ),
                              Text("${payType(e.payment)}")
                            ],
                          );
                        }).toList(),
                      ),
                    );
                  }
                  if(data.pay_status == "1" || data.status == "30"){
                    selectView = Container(
                      alignment: Alignment.centerRight,
                      child: Text("${payType(data.pay_type)}",style: TextStyle(color: AppColors.primaryColor),),
                    );
                  }
                  return  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        height: 165,
                        alignment: Alignment.topCenter,
                        padding: EdgeInsets.only(top: 12,bottom: 6),
                        color: AppColors.primaryColor,
                        width: double.infinity,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            ClipOval(
                              child: Container(
                                height: 50,
                                width: 50,
                                child: Image.asset(Utils.getImgPath("ic_logo"),fit: BoxFit.fill,),
                              ),
                            ),
                            SizedBox(height: 12,),
                            Text("${_showStatus(data.status ?? "")}${_showAppeal(data)}",style: TextStyle(color: Colors.white,fontSize: 17),),
                            SizedBox(height: 8,),
                            Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text("${_showStatusTips(data.status ?? "")}",style: TextStyle(color: Colors.white,fontSize: 15),),
                                Offstage(
                                    offstage: timeOut > 0 && data.status == "10" ? false : true,
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Text("${message['trad74']}",style: TextStyle(color: Colors.white,fontSize: 15),),
                                        SizedBox(width: 2,),
                                        Text(remainTimeStr.length > 0 ? remainTimeStr: "20:00",style: TextStyle(color: Colors.white,fontSize: 16),),
                                        SizedBox(width: 2,),
                                        Text("${message['trad75']}",style: TextStyle(color: Colors.white,fontSize: 15),),
                                      ],
                                    )
                                )
                              ],
                            ).addPadding(EdgeInsets.only(left: 12,right: 12))
                          ],
                        ),
                      ),
                      ///单价
                      ListTile(
                        leading: Text("${message['trad76']}"),
                        trailing: Text("${data.name == "MYR" ? 'MYR' : '¥'}${data.price}",style: TextStyle(color: AppColors.primaryColor),),
                      ),
                      Divider(),
                      ///数量
                      ListTile(
                        leading: Text("${message['trad77']}"),
                        trailing: Text("${data.quantity}",style: TextStyle(color: AppColors.primaryColor),),
                      ),
                      Divider(),
                      ///买家姓名
                      ListTile(
                        leading: Text("${message['trad78']}"),
                        trailing: Text("${data.buy_name}",style: TextStyle(color: AppColors.primaryColor),),
                      ),
                      Divider(),
                      ///卖家姓名
                      ListTile(
                        leading: Text("${message['trad79']}"),
                        trailing: Text("${data.sell_name}",style: TextStyle(color: AppColors.primaryColor),),
                      ),
                      Divider(),
                      ///联系方式
                      Offstage(
                        offstage: _mobileOffstage(data),
                        child: Column(
                          children: [
                            ListTile(
                                leading: Text("${message['trad80']}"),
                                trailing: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text("${_orderMobile(data)}",style: TextStyle(color: AppColors.primaryColor),),
                                    SizedBox(width: 2,),
                                    Container(
                                      padding: EdgeInsets.symmetric(horizontal: 4),
                                      decoration: BoxDecoration(
                                          color: AppColors.primaryColor,
                                          borderRadius: BorderRadius.only(
                                            topRight: Radius.circular(6),
                                            bottomRight: Radius.circular(6),
                                          )
                                      ),
                                      child: Text("${message['trad81']}",style: TextStyle(fontSize: 12,color: Colors.white),),
                                    ).addGesture(() {
                                      String mobile = "";
                                      if (userId == data.uid) {
                                        mobile = data.sell_mobile;
                                      }
                                      if (userId == data.to_uid) {
                                        mobile = data.buy_mobile;
                                      }
                                      ClipboardData cd = new ClipboardData(text: mobile);
                                      Clipboard.setData(cd);
                                      ToastUtils.show("${message['trad117']}", context);
                                    })
                                  ],
                                )
                            ),
                            Divider(),
                          ],
                        ),
                      ),
                      ///总价
                      ListTile(
                          leading: Text("${message['trad82']}"),
                          trailing: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text("${data.name == "MYR" ? 'MYR' : '¥'}${data.total_price}",style: TextStyle(color: AppColors.primaryColor),),
                              SizedBox(width: 2,),
                              Container(
                                padding: EdgeInsets.symmetric(horizontal: 4),
                                decoration: BoxDecoration(
                                    color: AppColors.primaryColor,
                                    borderRadius: BorderRadius.only(
                                      topRight: Radius.circular(6),
                                      bottomRight: Radius.circular(6),
                                    )
                                ),
                                child: Text("${message['trad81']}",style: TextStyle(fontSize: 12,color: Colors.white),),
                              ).addGesture(() {
                                ClipboardData cd = new ClipboardData(text: data.total_price);
                                Clipboard.setData(cd);
                                ToastUtils.show("${message['trad117']}", context);
                              })
                            ],
                          )
                      ),
                      Divider(),
                      ///订单编号
                      ListTile(
                          leading: Text("${message['trad83']}"),
                          trailing: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text("${data.sn}",style: TextStyle(color: AppColors.primaryColor),),
                              SizedBox(width: 2,),
                              Container(
                                padding: EdgeInsets.symmetric(horizontal: 4),
                                decoration: BoxDecoration(
                                    color: AppColors.primaryColor,
                                    borderRadius: BorderRadius.only(
                                      topRight: Radius.circular(6),
                                      bottomRight: Radius.circular(6),
                                    )
                                ),
                                child: Text("${message['trad81']}",style: TextStyle(fontSize: 12,color: Colors.white),),
                              ).addGesture(() {
                                ClipboardData cd = new ClipboardData(text: data.sn);
                                Clipboard.setData(cd);
                                ToastUtils.show("${message['trad117']}", context);
                              })
                            ],
                          )
                      ),
                      Divider(),

                      ///显示收款方式
                      Offstage(
                        offstage: data.pay_status != "0" && (current == 1 && data.status != "20") ? false : true,
                        child: _showPayMent(data.pay_type,skName,skBank,skCard,alipayUrl,wxUrl,usdtUrl),
                      ),

                      Offstage(
                        offstage: data.pay_status == "2" ? false : true,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            ListTile(
                              leading: Text("${message['trad92']}"),
                              trailing: Text("${data.mark}",style: TextStyle(color: AppColors.primaryColor),),
                            ),
                            Divider(),
                          ],
                        ),
                      ),

                      ///data.status != "0" &&  current != 1
                      Offstage( /// userId == data.uid 相等时我为买家，否则我为卖家，卖家不显示支付方式以下view
                        offstage: data.status != "0" && (current != 1 || data.status != "10")? false : true,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Container(
                              padding: EdgeInsets.only(left: 15,right: 15,top: 15,bottom: 15),
                              child: Row(
                                children: [
                                  Text("${message['trad84']}"),
                                  SizedBox(width: 20,),
                                  Expanded(
                                    child: selectView
                                    // Container(
                                    //   alignment: Alignment.centerRight,
                                    //   child: Row(
                                    //     mainAxisSize: MainAxisSize.min,
                                    //     children: [
                                    //       Offstage(
                                    //         offstage: paySelectView,
                                    //         child: Wrap(
                                    //           spacing: 2,
                                    //           runSpacing: 3,
                                    //           children: data.payment.map((e){
                                    //             return Row(
                                    //               mainAxisSize: MainAxisSize.min,
                                    //               children: [
                                    //                 SizedBox(
                                    //                   child: Radio(
                                    //                       value: e.payment,
                                    //                       groupValue: _select,
                                    //                       onChanged: (value){
                                    //                         setState(() {
                                    //                           _select = value;
                                    //                         });
                                    //                       }
                                    //                   ),
                                    //                   width: 30,
                                    //                   height: 30,
                                    //                 ),
                                    //                 Text("${payType(e.payment)}")
                                    //               ],
                                    //             );
                                    //           }).toList(),
                                    //         ),
                                    //       ),
                                    //       Offstage(
                                    //         offstage: data.pay_status == "1" || data.status == "30" ? false : true,
                                    //         child: Text("${payType(data.pay_type)}",style: TextStyle(color: AppColors.primaryColor),),
                                    //       )
                                    //     ],
                                    //   )
                                    // )
                                  )
                                ],
                              ),
                            ),
                            // Divider(),
                            Divider(),
                          ],
                        ),
                      ),
                      Offstage(
                          offstage: payImageView,
                          child: Container(
                            padding: EdgeInsets.only(left: 12,top: 12,bottom: 12),
                            child: Image.network("${data.certificate ?? ''}",width: 130,height: 130,fit: BoxFit.fill,).addGesture(() {
                              NavigatorUtil.navigateToPage(context, NetImagePreviewPage(listPath: [data.certificate],));
                            }),
                          )
                      ),


                      ///银行卡显示内容
                      Offstage(
                        offstage: _select == "1" ? false : true,
                        child: Column(
                          children: [
                            ListTile(
                                leading: Text("${message['trad88']}"),
                                trailing: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text("$skName",style: TextStyle(color: AppColors.primaryColor),),
                                    SizedBox(width: 2,),
                                    Container(
                                      padding: EdgeInsets.symmetric(horizontal: 4),
                                      decoration: BoxDecoration(
                                          color: AppColors.primaryColor,
                                          borderRadius: BorderRadius.only(
                                            topRight: Radius.circular(6),
                                            bottomRight: Radius.circular(6),
                                          )
                                      ),
                                      child: Text("${message['trad81']}",style: TextStyle(fontSize: 12,color: Colors.white),),
                                    ).addGesture(() {
                                      ClipboardData cd = new ClipboardData(text: skName);
                                      Clipboard.setData(cd);
                                      ToastUtils.show("${message['trad117']}", context);
                                    })
                                  ],
                                )
                            ),
                            Divider(),
                            ListTile(
                                leading: Text("${message['trad89']}"),
                                trailing: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text("$skBank",style: TextStyle(color: AppColors.primaryColor),),
                                    SizedBox(width: 2,),
                                    Container(
                                      padding: EdgeInsets.symmetric(horizontal: 4),
                                      decoration: BoxDecoration(
                                          color: AppColors.primaryColor,
                                          borderRadius: BorderRadius.only(
                                            topRight: Radius.circular(6),
                                            bottomRight: Radius.circular(6),
                                          )
                                      ),
                                      child: Text("${message['trad81']}",style: TextStyle(fontSize: 12,color: Colors.white),),
                                    ).addGesture(() {
                                      ClipboardData cd = new ClipboardData(text: skBank);
                                      Clipboard.setData(cd);
                                      ToastUtils.show("${message['trad117']}", context);
                                    })
                                  ],
                                )
                            ),
                            Divider(),
                            ListTile(
                                leading: Text("${message['trad90']}"),
                                trailing: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text("$skCard",style: TextStyle(color: AppColors.primaryColor),),
                                    SizedBox(width: 2,),
                                    Container(
                                      padding: EdgeInsets.symmetric(horizontal: 4),
                                      decoration: BoxDecoration(
                                          color: AppColors.primaryColor,
                                          borderRadius: BorderRadius.only(
                                            topRight: Radius.circular(6),
                                            bottomRight: Radius.circular(6),
                                          )
                                      ),
                                      child: Text("${message['trad81']}",style: TextStyle(fontSize: 12,color: Colors.white),),
                                    ).addGesture(() {
                                      ClipboardData cd = new ClipboardData(text: skCard);
                                      Clipboard.setData(cd);
                                      ToastUtils.show("${message['trad117']}", context);
                                    })
                                  ],
                                )
                            ),
                            Divider(),
                          ],
                        ),
                      ),
                      ///支付宝显示内容
                      Offstage(
                        offstage: _select == "2" ? false : true,
                        child: Column(
                          children: [
                            ListTile(
                              leading: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Text("${message['trad93']}"),
                                  Text("(${message['trad94']})",style: TextStyle(color: AppColors.primaryColor),),
                                ],
                              ),
                              trailing: Image.asset(Utils.getImgPath('ic_trad_ewm'),width: 35,height: 35,),
                              onTap: (){
                                NavigatorUtil.navigateToPage(context, NetImagePreviewPage(listPath: [alipayUrl],));
                              },
                            ),
                            Divider(),
                            // Container(
                            //   padding: EdgeInsets.only(left: 15,top: 12),
                            //   alignment: Alignment.centerLeft,
                            //   child: Column(
                            //     mainAxisSize: MainAxisSize.min,
                            //     crossAxisAlignment: CrossAxisAlignment.start,
                            //     children: [
                            //       Text("${message['trad95']}"),
                            //       SizedBox(height: 12,),
                            //       GestureDetector(
                            //         child: alipayImage,
                            //         onTap: () async{
                            //           closeKeyboard(context);
                            //           PickedFile value = await _picker.getImage(source: ImageSource.gallery, imageQuality: 100,);
                            //           File file = File(value.path);
                            //           File newFile = await ImageUtils.imageCompressAndGetFile(file);
                            //           LoadingApi.func(TradRepository().uploadImage(newFile,3), context, complete: (v) {
                            //             if (v == null) {
                            //               return;
                            //             }
                            //             setState(() {
                            //               alipayUploadUrl = v;
                            //             });
                            //           });
                            //         },
                            //       )
                            //     ],
                            //   ),
                            // )
                          ],
                        ),
                      ),
                      ///TNG显示内容
                      Offstage(
                        offstage: _select == "5" ? false : true,
                        child: Column(
                          children: [
                            ListTile(
                              leading: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Text("${message['trad93']}"),
                                  Text("(${message['trad94']})",style: TextStyle(color: AppColors.primaryColor),),
                                ],
                              ),
                              trailing: Image.asset(Utils.getImgPath('ic_trad_ewm'),width: 35,height: 35,),
                              onTap: (){
                                NavigatorUtil.navigateToPage(context, NetImagePreviewPage(listPath: [tngUrl],));
                              },
                            ),
                            Divider(),
                          ],
                        ),
                      ),
                      ///微信显示内容
                      Offstage(
                        offstage: _select == "3" ? false : true,
                        child: Column(
                          children: [
                            ListTile(
                              leading: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Text("${message['trad93']}"),
                                  Text("(${message['trad94']})",style: TextStyle(color: AppColors.primaryColor),),
                                ],
                              ),
                              trailing: Image.asset(Utils.getImgPath('ic_trad_ewm'),width: 35,height: 35,),
                              onTap: (){
                                NavigatorUtil.navigateToPage(context, NetImagePreviewPage(listPath: [wxUrl],));
                              },
                            ),
                            Divider(),
                            // Container(
                            //   padding: EdgeInsets.only(left: 15,top: 12),
                            //   alignment: Alignment.centerLeft,
                            //   child: Column(
                            //     mainAxisSize: MainAxisSize.min,
                            //     crossAxisAlignment: CrossAxisAlignment.start,
                            //     children: [
                            //       Text("${message['trad95']}"),
                            //       SizedBox(height: 12,),
                            //       GestureDetector(
                            //         child: wxImage,
                            //         onTap: () async{
                            //           closeKeyboard(context);
                            //           PickedFile value = await _picker.getImage(source: ImageSource.gallery, imageQuality: 100,);
                            //           File file = File(value.path);
                            //           File newFile = await ImageUtils.imageCompressAndGetFile(file);
                            //           LoadingApi.func(TradRepository().uploadImage(newFile,3), context, complete: (v) {
                            //             if (v == null) {
                            //               return;
                            //             }
                            //             setState(() {
                            //               wxUploadUrl = v;
                            //             });
                            //           });
                            //         },
                            //       )
                            //     ],
                            //   ),
                            // )
                          ],
                        ),
                      ),

                      ///USDT显示内容
                      Offstage(
                        offstage: _select == "4" ? false : true,
                        child: Column(
                          children: [
                            ListTile(
                                leading: Text("${message['trad91']}"),
                                trailing: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text("$usdtUrl",style: TextStyle(color: AppColors.primaryColor),),
                                    SizedBox(width: 2,),
                                    Container(
                                      padding: EdgeInsets.symmetric(horizontal: 4),
                                      decoration: BoxDecoration(
                                          color: AppColors.primaryColor,
                                          borderRadius: BorderRadius.only(
                                            topRight: Radius.circular(6),
                                            bottomRight: Radius.circular(6),
                                          )
                                      ),
                                      child: Text("${message['trad81']}",style: TextStyle(fontSize: 12,color: Colors.white),),
                                    ).addGesture(() {
                                      ClipboardData cd = new ClipboardData(text: usdtUrl);
                                      Clipboard.setData(cd);
                                      ToastUtils.show("${message['trad117']}", context);
                                    })
                                  ],
                                )
                            ),
                            Divider(),
                          ],
                        ),
                      ),


                      Offstage(
                        offstage: (data.pay_status == "0" || data.pay_status == "2") && data.status != "0" && current != 1 && data.status != "30" ? false : true,
                        child:  Container(
                          padding: EdgeInsets.only(left: 15,top: 12),
                          alignment: Alignment.centerLeft,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text("${message['trad95']}"),
                              SizedBox(height: 12,),
                              GestureDetector(
                                child: uploadByImage,
                                onTap: () async{
                                  closeKeyboard(context);
                                  PickedFile value = await _picker.getImage(source: ImageSource.gallery, imageQuality: 100,);
                                  File file = File(value.path);
                                  File newFile = await ImageUtils.imageCompressAndGetFile(file);
                                  LoadingApi.func(TradRepository().uploadImage(newFile,3), context, complete: (v) {
                                    if (v == null) {
                                      return;
                                    }
                                    setState(() {
                                      uploadBuyImage = v;
                                    });
                                  });
                                },
                              )
                            ],
                          ),
                        ),
                      ),
                      SizedBox(height: 50,),


                      Container(
                        alignment: Alignment.center,
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            ///申诉
                            Offstage(
                                offstage: data.pay_status == "2" && data.appeal == "0" && current!=1 && data.status != "30" ? false : true,
                                child: _buttonView("${message['trad97']}",data.id,1)
                            ),

                            ///取消订单
                            Offstage(
                                offstage: (data.status == "20" || data.status == "10") && userId == data.uid ? false : true,
                                child: _buttonView("${message['trad98']}",data.id,2,p: data.prompt)
                            ),

                            ///驳回凭证
                            Offstage(
                                offstage: userId == data.to_uid && data.status == "20" && current==1 && data.pay_status == "1" ? false : true,
                                child: _buttonView("${message['trad99']}",data.id,3)
                            ),

                            ///确认交易
                            Offstage(
                                offstage: userId == data.to_uid && data.status == "20" && current==1 ? false : true,
                                child: _buttonView("${message['trad100']}",data.id,4)
                            ),

                            ///已支付
                            Offstage(
                                offstage: (data.pay_status == "0" || data.pay_status == "2") && current!=1 && data.status != "0" && data.status != "30" ? false : true,
                                child: _buttonView("${message['trad101']}",data.id,5)
                            )
                          ],
                        ),
                      ),
                      SizedBox(height: 20,),
                    ],
                  );
                }
            )
        ),
      )
    );
  }


  Widget _buttonView(String text,String id,int type,{String p}){
    return Container(
      width: 110,
      height: 40,
      margin: EdgeInsets.symmetric(horizontal: 6),
      child: ElevatedButton(
        child: Text(text,style: TextStyle(color: (type == 2 || type == 3) ? HexColor("#AB5A1E") : Colors.white),),
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all((type == 2 || type == 3) ? HexColor("#FDDCBB"):AppColors.primaryColor),
          shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),//圆角弧度
        ),
        onPressed: (){
          switch(type){
            case 2:
              cancelOrder(id,p);
              break;
            case 5:
              paySuccess(id);
              break;
            case 1:
              NavigatorUtil.navigateToPage(context, AppealOrderPage(id: id,)).then((value){
                if(value != null){
                  BlocProvider.of<OrderItemInfoBloc>(ctx).add(IdHttpEvent(int.parse(widget.id)));
                }
              });
              break;
            case 3:
              backImage(id);
              break;
            case 4:
              orderRelease(id);
              break;
          }
        },
      ),
    );
  }

  void orderRelease(String id) async{
    String pwd = await _inputTradePassword();
    if (pwd == null) {
      ToastUtils.show("${message['cp4']}", context);
      return;
    }
    LoadingApi.func(TradRepository().orderRelease(id, pwd), context,complete: (v){
      Navigator.of(context).pop(1);
      ToastUtils.show("${message['Success']}", context);
    },error: (e){
      ToastUtils.show("$e", context);
    });
  }
  Future<String> _inputTradePassword() async {
    String pwd = await showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return PayDialog();
      },
    );
    if (pwd == null) {
      return null;
    }
    return pwd;
  }
  void backImage(String id){
    showDialog(context: context, builder: (context){
      return BackTextDialog();
    }).then((value){
      if(value != null){
        LoadingApi.func(TradRepository().orderTurnMark(id, value), context,complete: (v){
          BlocProvider.of<OrderItemInfoBloc>(ctx).add(IdHttpEvent(int.parse(widget.id)));
          ToastUtils.show("${message['Success']}", context);
        },error: (e){
          ToastUtils.show("$e", context);
        });
      }
    });
  }


  ///已支付
  void paySuccess(String id){
    if(_select == "0"){
      ToastUtils.show("${message['trad118']}", context);
      return;
    }
    // String url;
    // if(_select == "2"){
    //   url = alipayUploadUrl;
    // }else if(_select == "3"){
    //   url = wxUploadUrl;
    // }
    LoadingApi.func(TradRepository().orderPayment(id,uploadBuyImage,_select), context,complete: (v){
      BlocProvider.of<OrderItemInfoBloc>(ctx).add(IdHttpEvent(int.parse(widget.id)));
    },error: (e){
      ToastUtils.show("$e", context);
    });
  }

  ///取消订单
  void cancelOrder(String id,String prompt){
    showCupertinoDialog(
        context: context,
        builder: (cancelCtx) {
          return CupertinoAlertDialog(
            title: Text('${message['trad115']}'),
            content: Text('$prompt'),
            actions: <Widget>[
              CupertinoDialogAction(child: Text('${message['address14']}'),onPressed: (){
                Navigator.pop(cancelCtx);
              },),
              CupertinoDialogAction(child: Text('${message['address15']}'),onPressed: (){
                Navigator.pop(cancelCtx);
                LoadingApi.func(TradRepository().cancelAdOrder(id), context,complete: (v){
                  ToastUtils.show("$v", context);
                  Navigator.of(context).pop(1);
                },error: (e){
                  ToastUtils.show("$e", context);
                });
              },),
            ],
          );
        });
  }










  String _showAppeal(TradOrderDetail item){
    if(item.appeal == "1"){
      return "(${message['trad72']})"; ///申诉中
    }else{
      if(item.pay_status == "2"){
        return "(${message['trad73']})"; ///已驳回凭证
      }else{
        return "";
      }
    }
  }
  ///状态
  String _showStatus(String status){
    switch(status){
      case "0":
        return "${message['trad107']}"; ///已取消
      case "10":
        return "${message['trad108']}"; ///未付款
      case "20":
        return "${message['trad109']}"; ///已付款
      case "30":
        return "${message['trad110']}"; ///已完成
      default:
        return "";
    }
  }
  ///状态
  String _showStatusTips(String status){
    switch(status){
      case "0":
        return "${message['trad111']}";
      case "10":
        return "${message['trad112']}";
      case "20":
        return "${message['trad113']}";
      case "30":
        return "${message['trad114']}";
      default:
        return "";
    }
  }

  Widget _showPayMent(String pay_type,String skName,String skBank,String skCard,String alipayUrl,String wxUrl,String usdtUrl){
    Widget child;
    if(pay_type == "1"){
      child = Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ListTile(
              leading: Text("${message['trad88']}"),
              trailing: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text("$skName",style: TextStyle(color: AppColors.primaryColor),),
                  SizedBox(width: 2,),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 4),
                    decoration: BoxDecoration(
                        color: AppColors.primaryColor,
                        borderRadius: BorderRadius.only(
                          topRight: Radius.circular(6),
                          bottomRight: Radius.circular(6),
                        )
                    ),
                    child: Text("${message['trad81']}",style: TextStyle(fontSize: 12,color: Colors.white),),
                  ).addGesture(() {
                    ClipboardData cd = new ClipboardData(text: skName);
                    Clipboard.setData(cd);
                    ToastUtils.show("${message['trad117']}", context);
                  })
                ],
              )
          ),
          Divider(),
          ListTile(
              leading: Text("${message['trad89']}"),
              trailing: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text("$skBank",style: TextStyle(color: AppColors.primaryColor),),
                  SizedBox(width: 2,),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 4),
                    decoration: BoxDecoration(
                        color: AppColors.primaryColor,
                        borderRadius: BorderRadius.only(
                          topRight: Radius.circular(6),
                          bottomRight: Radius.circular(6),
                        )
                    ),
                    child: Text("${message['trad81']}",style: TextStyle(fontSize: 12,color: Colors.white),),
                  ).addGesture(() {
                    ClipboardData cd = new ClipboardData(text: skBank);
                    Clipboard.setData(cd);
                    ToastUtils.show("${message['trad117']}", context);
                  })
                ],
              )
          ),
          Divider(),
          ListTile(
              leading: Text("${message['trad90']}"),
              trailing: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text("$skCard",style: TextStyle(color: AppColors.primaryColor),),
                  SizedBox(width: 2,),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 4),
                    decoration: BoxDecoration(
                        color: AppColors.primaryColor,
                        borderRadius: BorderRadius.only(
                          topRight: Radius.circular(6),
                          bottomRight: Radius.circular(6),
                        )
                    ),
                    child: Text("${message['trad81']}",style: TextStyle(fontSize: 12,color: Colors.white),),
                  ).addGesture(() {
                    ClipboardData cd = new ClipboardData(text: skCard);
                    Clipboard.setData(cd);
                    ToastUtils.show("${message['trad117']}", context);
                  })
                ],
              )
          ),
          Divider(),
        ],
      );
    }else if(pay_type == "2"){
      child = Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ListTile(
              leading: Text("${message['trad33']}",style: TextStyle(fontSize: 14,color: AppColors.textColor),),
              trailing: Text("${message['trad37']}",style: TextStyle(color: AppColors.primaryColor),)
          ),
          Divider(),
        ],
      );
    }else if(pay_type == "3"){
      child = Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ListTile(
            leading: Text("${message['trad33']}",style: TextStyle(fontSize: 14,color: AppColors.textColor),),
            trailing: Text("${message['trad38']}",style: TextStyle(color: AppColors.primaryColor),)
          ),
          Divider(),
        ],
      );
    }else if(pay_type == "4"){
      child = Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ListTile(
              leading: Text("${message['trad91']}"),
              trailing: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text("$usdtUrl",style: TextStyle(color: AppColors.primaryColor),),
                  SizedBox(width: 2,),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 4),
                    decoration: BoxDecoration(
                        color: AppColors.primaryColor,
                        borderRadius: BorderRadius.only(
                          topRight: Radius.circular(6),
                          bottomRight: Radius.circular(6),
                        )
                    ),
                    child: Text("${message['trad81']}",style: TextStyle(fontSize: 12,color: Colors.white),),
                  ).addGesture(() {
                    ClipboardData cd = new ClipboardData(text: usdtUrl);
                    Clipboard.setData(cd);
                    ToastUtils.show("${message['trad117']}", context);
                  })
                ],
              )
          ),
          Divider(),
        ],
      );
    }else if(pay_type == "5"){
      child = Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ListTile(
              leading: Text("${message['trad33']}",style: TextStyle(fontSize: 14,color: AppColors.textColor),),
              trailing: Text("${message['text30']}",style: TextStyle(color: AppColors.primaryColor),)
          ),
          Divider(),
        ],
      );
    }
    return child;
  }


  String payType(String type){
    switch(type){
      case "1":
        return "${message['trad85']}";
      case "2":
        return "${message['trad86']}";
      case "3":
        return "${message['trad87']}";
      case "4":
        return "USDT";
      case "5":
        return "TNG";
      default:
        return "";
    }
  }


  String _orderMobile(TradOrderDetail data){
    String mobile = "";
    if (userId == data.uid) {
      mobile = data.sell_mobile;
    }
    if (userId == data.to_uid) {
      mobile = data.buy_mobile;
    }

    return mobile;
  }

  bool _mobileOffstage(TradOrderDetail data){
    bool temp = true;
    if (userId == data.uid) {
      if(data.sell_mobile == ""){
        temp = true;
      }else{
        temp = false;
      }
    }
    if (userId == data.to_uid) {
      if(data.buy_mobile == ""){
        temp = true;
      }else{
        temp = false;
      }
    }
    return temp;
  }
}




///驳回
class BackTextDialog extends StatefulWidget{
  @override
  BackTextDialogState createState() => BackTextDialogState();
}
class BackTextDialogState extends State<BackTextDialog>{
  final _controller = TextEditingController();

  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Material(
      color: Colors.transparent,
      child: WillPopScope(
        child: Center(
          child: Padding(
              padding: EdgeInsets.only(left: 40, right: 40),
              child: AspectRatio(
                  aspectRatio: 1.4,
                  child: Container(
                      margin: EdgeInsets.only(bottom: 8),
                      padding: EdgeInsets.only(top: 12),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(6)),
                          color: Colors.white
                      ),
                      child: Stack(
                        children: [
                          Column(
                            children: [
                              Text("${message['trad105']}",style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),),
                              Container(
                                height: 90,
                                margin: EdgeInsets.all(12),
                                padding: EdgeInsets.all(12),
                                decoration: new BoxDecoration(
                                  borderRadius: new BorderRadius.circular((5.0)),
                                  border: Border.all(color: HexColor("#F6F6F6"),width: 1)
                                ),
                                child: TextFormFieldWidget(
                                  hintText: "${message['trad106']}",
                                  maxLines: 10,
                                  needUnderline: false,
                                  maxLength: 100,
                                  controller: _controller,
                                ),
                              ),
                            ],
                          ),
                          Positioned(
                            bottom: 0,
                            left: 0,
                            right: 0,
                            child: Container(
                              margin: EdgeInsets.only(top: 18),
                              child: Column(
                                children: [
                                  Divider(),
                                  Row(
                                    children: [
                                      Flexible(
                                          flex: 1,
                                          child: Container(
                                            width: double.infinity,
                                            height: 50,
                                            alignment: Alignment.center,
                                            child: Text("${message['address14']}",style: TextStyle(color: HexColor("#999999"),fontSize: 16),),
                                          ).addGesture(() {
                                            Navigator.of(context).pop();
                                          })
                                      ),
                                      ColoredBox(color: HexColor("#E8E8E8"),
                                        child: SizedBox(width: 1,height: 50,),
                                      ),
                                      Flexible(
                                          flex: 1,
                                          child: Container(
                                            width: double.infinity,
                                            height: 50,
                                            alignment: Alignment.center,
                                            child: Text("${message['address15']}",style: TextStyle(color: AppColors.primaryColor,fontSize: 16),),
                                          ).addGesture(() {
                                            if(_controller.text == ""){
                                              // ToastUtils.show("请输入", context);
                                              return;
                                            }
                                            Navigator.of(context).pop(_controller.text);
                                          })
                                      )
                                    ],
                                  )
                                ],
                              ),
                            ),
                          )
                        ],
                      )
                  )
              )
          ),
        ),
        onWillPop: () async {
          return true;
        },
      ),
    );
  }
}